{%- assign facebook = storeConfig.facebook | strtoarray -%}
{% get_pixels_domain list={facebook} %}
{%- assign facebook = list -%}
{%- if facebook -%}
        <!-- Facebook Pixel Code -->
    <script>
        !function (f, b, e, v, n, t, s) {
            if (f.fbq) return;
            n = f.fbq = function () {
                n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments)
            };
            if (!f._fbq) f._fbq = n;
            n.push = n;
            n.loaded = !0;
            n.version = '2.0';
            n.queue = [];
            t = b.createElement(e);
            t.async = !0;
            t.src = v;
            s = b.getElementsByTagName(e)[0];
            s.parentNode.insertBefore(t, s)
        }(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
        var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);

        function yfbservertag(event_name, obj, event_id) {
                //Pay success callback
                const purchase = {
                    em:oemcart_user_email,
                    country:oemcart_client_country
                };
                {%- if controller == 'order' and action == 'success' -%}
                purchase.em = "{{order.customer_email}}";
                purchase.ph = "{{order.shipping_address.phone}}";
                purchase.ln = "{{order.shipping_address.last_name}}";
                purchase.fn = "{{order.shipping_address.first_name}}";
                purchase.ct = "{{order.shipping_address.city}}";
                purchase.st = "{{order.shipping_address.province}}";
                purchase.zp = "{{order.shipping_address.zip}}";
                purchase.country = "{{order.shipping_address.country_code}}";
                {%- endif -%}

                const fbParams = {
                    /*********  start   ********/
                    "visitor_id": oemcart_global_unique_id,
                    "country_code": oemcart_client_country,
                    "event_name": event_name,
                    "event_id": event_id,
                    "event_source_url": location.href,
                    "action_source": 'website',
                    "user_data": {
                        "client_user_agent": navigator.userAgent,
                        "fbc": oemcartCollect.getCookie("_fbc") || `{{request_param|facebookfbc}}`,
                        "fbp": oemcartCollect.getCookie("_fbp") || '{{1|facebookfbp}}',
                        ...purchase
                    },
                    "custom_data": obj
                }
                fetch('/homeapi/facebook', {
                    method: "POST",
                    body: JSON.stringify(fbParams)
                })
        };
            {% for pixel in facebook %}
            fbq('init', '{{ pixel.facebook_pixel_id }}', {external_id:'{{visit_id}}'}, {}, {eventID: fb_eventid});
            fbq('trackSingle', '{{ pixel.facebook_pixel_id }}', 'PageView', {'event_category': '{{template}}'}, {eventID: fb_eventid});
            {% endfor %}
            yfbservertag('PageView',{'event_category': '{{template}}'}, fb_eventid);

        {%- if template == 'product_detail' -%}
            const fbqViewContentParams = {
                content_name:  oemcart_product.title,
                content_category: '{{ product.product_type | escape | append: ' '}}'.replace(/\s+$/g, ""),
                value: '{{ product.variant.price}}',
                content_type: 'product',
                content_ids: ["{{ product.spu | escape}}"],
                currency: '{{ base_currency.standard_code }}'
            };
            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.facebook_pixel_id }}', 'ViewContent', fbqViewContentParams, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('ViewContent',fbqViewContentParams,fb_eventid)
        
        {%- elsif template == 'search_detail' and search.keywords -%}
            const fbqSearchParams = {
                search_string: '{{ search.keywords | escape | append: ' '}}'.replace(/\s+$/g, ""),
                content_type: 'product',
                currency: oemcart_currency_code,
                contents:[]
            };
            {%- for product in search.products -%}
            fbqSearchParams.contents.push({
                id: '{{ product.spu  | escape }}',
                quantity: 1,
                item_price: "{{ product.variant.price }}"
            });
            {%- endfor -%}

            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.facebook_pixel_id }}', 'Search', fbqSearchParams, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('Search',fbqSearchParams,fb_eventid)

        {%- elsif controller == 'order' and action == 'success' -%}
            const fbqPurchaseParams = {
                {% if storeConfig.enable_ga %}
                value: "{{ order.current_subtotal_price| plus: order.current_coupon_price| plus: order.current_promotion_price }}",
                {% else %}
                value: "{{ order.total_price }}",
                {% endif %}
                currency: '{{ order.currency_code }}',
                contents:[],
                content_type:'product',
                order_id: '{{order.order_number}}',
                num_items: '{{order.total_num}}'
            };
            {%- for product in order.products -%}
                fbqPurchaseParams.contents.push({
                    id: '{{ product.spu  | escape}}',
                    quantity: "{{ product.quantity }}",
                    item_price: "{{ product.discount_price  | default : product.price }}"
                });
            {%- endfor -%}

            {% capture pixels %}facebook_pixels_{{order.id}}{% endcapture %}
            {% get_cache key={pixels} var_name=facebook_pixels_status%}
            {% if facebook_pixels_status == 0 %}

            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.facebook_pixel_id }}', 'Purchase', fbqPurchaseParams, {eventID: "{{order.order_number}}"});
            {%- endfor -%}
            {% comment %} yfbservertag('Purchase', fbqPurchaseParams, '{{order.order_number}}'); {% endcomment %}

            {% endif %}

        {%- elsif template == 'blog_detail' -%}
            const fbqBlogParams = {
                'event_category': '{{template}}',
                'event_label': '{{blog.title | escape}}',
                'event_value': '{{blog.id}}'
            };
            {%- for pixel in facebook -%}
            fbq('trackSingleCustom', '{{ pixel.facebook_pixel_id }}', 'page_view_event',fbqBlogParams, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('page_view_event',fbqBlogParams, fb_eventid);

        {%- elsif template == 'collection_detail' -%}
            const fbqCollectionParams = {
                'event_category': '{{template}}',
                'event_label': '{{collection.title | escape}}',
                'event_value': '{{collection.id}}'
            };
            {%- for pixel in facebook -%}
            fbq('trackSingleCustom', '{{ pixel.facebook_pixel_id }}', 'page_view_event',fbqCollectionParams, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('page_view_event',fbqCollectionParams, fb_eventid);
        {%- elsif template == 'page_detail' -%}
            const fbqPageParmas = {
                'event_category': '{{template}}',
                'event_label': '{{page.title | escape}}',
                'event_value': '{{page.id}}'
            };
            {%- for pixel in facebook -%}
            fbq('trackSingleCustom', '{{ pixel.facebook_pixel_id }}','page_view_event',fbqPageParmas, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('page_view_event',fbqPageParmas, fb_eventid);

        {%- endif -%}
    </script>
    {%- for pixel in facebook -%}
        <noscript><img height='1' width='1'
                       src='https://www.facebook.com/tr?id="{{ pixel.facebook_pixel_id }}"&ev=PageView&noscript=1'/>
        </noscript>
    {%- endfor -%}


<script>
    function callback_facebook_add_to_cart(ecdata) {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            const fbqAddToCartParmas = {
                content_type: 'product',
                content_category: ecdata['ec_data_category'],
                content_name: ecdata['ec_data_name'],
                currency: "{{ base_currency.standard_code }}",
                value: ecdata['ec_data_price']*ecdata['ec_data_quantity'],
                contents: [{id: ecdata['ec_data_spu'], quantity: ecdata['ec_data_quantity'], item_price: ecdata['ec_data_price']}]
            };
            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.facebook_pixel_id }}', 'AddToCart', fbqAddToCartParmas, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('AddToCart',fbqAddToCartParmas, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_generate_lead() {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.facebook_pixel_id }}', 'Lead', {}, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('Lead', {}, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_login() {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            {%- for pixel in facebook -%}
            fbq('trackSingleCustom', '{{ pixel.facebook_pixel_id }}', 'login',{}, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('login',{}, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_begin_checkout() {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.facebook_pixel_id }}', 'InitiateCheckout', {}, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('InitiateCheckout',{}, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_share_product(ecdata, platform) {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            const fbqShareProductParams = {
                'event_category':ecdata['ec_data_category'],
                'event_label':ecdata['ec_data_spu'],
                'event_value':ecdata['ec_data_quantity']
            };
            {%- for pixel in facebook -%}
            fbq('trackSingleCustom', '{{ pixel.facebook_pixel_id }}', 'share_product',fbqShareProductParams, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('share_product',fbqShareProductParams,fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_remove_from_cart(ecdata) {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            const fbqRemoveFromCart = {
                'event_category':ecdata['ec_data_category'],
                'event_label':ecdata['ec_data_spu'],
                'event_value':ecdata['ec_data_quantity']
            };
            {%- for pixel in facebook -%}
            fbq('trackSingleCustom', '{{ pixel.facebook_pixel_id }}', 'remove_from_cart',fbqRemoveFromCart, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('remove_from_cart',fbqRemoveFromCart, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_sign_up() {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.facebook_pixel_id }}', 'CompleteRegistration',{}, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('CompleteRegistration',{}, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_add_address_information() {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            {%- for pixel in facebook -%}
            fbq('trackSingleCustom', '{{ pixel.facebook_pixel_id }}', 'add_address_information',{}, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('add_address_information',{}, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_add_shipping_information() {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            {%- for pixel in facebook -%}
            fbq('trackSingleCustom', '{{ pixel.facebook_pixel_id }}', 'add_shipping_information',{}, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('add_shipping_information',{}, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_add_payment_information() {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.facebook_pixel_id }}', 'AddPaymentInfo',{}, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('AddPaymentInfo',{}, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_to_wishlist() {
        {% if facebook %}
        var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
        {% for pixel in facebook %}
        fbq('trackSingle', '{{ pixel.facebook_pixel_id }}', 'AddToWishlist', {}, { eventID: fb_eventid });
        {% endfor %}
        yfbservertag('AddToWishlist', {}, fb_eventid);
        {% endif %}
    }
</script>

<!-- End Facebook Pixel Code -->
 {%- endif -%}
 